package com.tulei.qqread;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.ui.ApplicationFrame;
import org.jfree.chart.ui.UIUtils;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

import javax.swing.*;
import java.awt.*;
import java.sql.*;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author TuLei
 * @Date 2024-07-14 19:07
 **/

public class BookPicture {

    private static final String DB_URL = "jdbc:mysql://localhost:3306/admin";
    private static final String USER = "root";
    private static final String PASS = "123456";

    public static void main(String[] args) {
        List<Book> books = new ArrayList<>();

        // 查询数据库
        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
            Statement stmt = conn.createStatement();
            String sql = "SELECT * FROM book";
            ResultSet rs = stmt.executeQuery(sql);

            while (rs.next()) {
                String title = rs.getString("title");
                String author = rs.getString("author");
                String kind = rs.getString("kind");
                String intro = rs.getString("intro");
                String serial = rs.getString("serial");
                String count = rs.getString("count");
                Book book = new Book(title, intro, author, kind, serial, count);
                books.add(book);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }


        ApplicationFrame frame = new ApplicationFrame("Book Charts");

        // 创建四个图表的面板
        ChartPanel pieChartPanel = new ChartPanel(createPieChart(books));
        ChartPanel lineChartPanel = new ChartPanel(createLineChart(books));
        ChartPanel barChartPanel = new ChartPanel(createPieChart2(books));
        ChartPanel scatterPlotPanel = new ChartPanel(createBarChart(books));

        // 使用 GridLayout 布局将四个图表面板放在同一个窗口中
        JPanel panel = new JPanel(new GridLayout(2, 2));
        panel.add(pieChartPanel);
        panel.add(barChartPanel);
        panel.add(lineChartPanel);
        panel.add(scatterPlotPanel);

        frame.setContentPane(panel);
        frame.pack();
        UIUtils.centerFrameOnScreen(frame);
        frame.setVisible(true);
    }

    private static JFreeChart createPieChart(List<Book> books) {
        // 定义字数区间
        Map<String, Integer> wordCountCategories = new HashMap<>();
        wordCountCategories.put("0-200万字", 0);
        wordCountCategories.put("200-500万字", 0);
        wordCountCategories.put("500-1000万字", 0);
        wordCountCategories.put("1000+万字", 0);

        // 分类书籍
        for (Book book : books) {
            // 使用正则表达式替换掉"万字"并转换为double
            double wordCount = Double.parseDouble(book.getCount().replace("万字", ""));
            if (wordCount <= 200) {
                wordCountCategories.put("0-200万字", wordCountCategories.getOrDefault("0-200万字", 0) + 1);
            } else if (wordCount <= 500) {
                wordCountCategories.put("200-500万字", wordCountCategories.getOrDefault("200-500万字", 0) + 1);
            } else if (wordCount <= 1000) {
                wordCountCategories.put("500-1000万字", wordCountCategories.getOrDefault("500-1000万字", 0) + 1);
            } else {
                wordCountCategories.put("1000+万字", wordCountCategories.getOrDefault("1000+万字", 0) + 1);
            }
        }

        // 创建数据集
        DefaultPieDataset dataset = new DefaultPieDataset();
        for (Map.Entry<String, Integer> entry : wordCountCategories.entrySet()) {
            dataset.setValue(entry.getKey(), entry.getValue());
        }

        // 创建饼状图
        JFreeChart pieChart = ChartFactory.createPieChart(
                "书籍字数占比饼状图",
                dataset,
                true, true, false);

        // 设置标签生成器
        PiePlot plot = (PiePlot) pieChart.getPlot();
        plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}: {1}"));

        // 设置字体以支持中文字符
        Font font = Font.decode("SansSerif-PLAIN-12");
        Font font1 = Font.decode("SansSerif-PLAIN-20");
        plot.setLabelFont(font);
        pieChart.getTitle().setFont(font1);
        pieChart.getLegend().setItemFont(font);

        return pieChart;
    }


    private static JFreeChart createLineChart(List<Book> books) {
        Map<String, Integer> categoryCount = new HashMap<>();
        for (Book book : books) {
            String category = book.getKind();
            categoryCount.put(category, categoryCount.getOrDefault(category, 0) + 1);
        }

        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        for (Map.Entry<String, Integer> entry : categoryCount.entrySet()) {
            dataset.addValue(entry.getValue(), "Number of Books", entry.getKey());
        }

        JFreeChart lineChart = ChartFactory.createLineChart(
                "书籍种类折线图",
                "种类",
                "书籍数量",
                dataset,
                PlotOrientation.VERTICAL,
                true, true, false);

        CategoryPlot plot = (CategoryPlot) lineChart.getPlot();
        // 使用支持中文的字体
        // 使用支持中文的字体
        Font chineseFont = new Font("SimSun", Font.PLAIN, 12);
        Font chineseFont1 = new Font("SimSun", Font.PLAIN, 20);
        plot.getDomainAxis().setLabelFont(chineseFont);
        plot.getDomainAxis().setTickLabelFont(chineseFont);
        plot.getRangeAxis().setLabelFont(chineseFont);
        lineChart.getTitle().setFont(chineseFont1);
        lineChart.getLegend().setItemFont(chineseFont);

        // 设置折线图的渲染器
        LineAndShapeRenderer renderer = new LineAndShapeRenderer();
        plot.setRenderer(renderer);

        return lineChart;
    }


    private static JFreeChart createPieChart2(List<Book> books) {
        Map<String, Integer> serialCount = new HashMap<>();
        for (Book book : books) {
            String serial = book.getSerial();
            serialCount.put(serial, serialCount.getOrDefault(serial, 0) + 1);
        }

        DefaultPieDataset dataset = new DefaultPieDataset();
        for (Map.Entry<String, Integer> entry : serialCount.entrySet()) {
            dataset.setValue(entry.getKey(), entry.getValue());
        }

        JFreeChart pieChart = ChartFactory.createPieChart(
                "书籍连载状态饼状图",
                dataset,
                true, true, false);

        PiePlot plot = (PiePlot) pieChart.getPlot();
        plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}: {1}"));

        // 使用系统字体以支持中文字符
        Font font = Font.decode("SansSerif-PLAIN-12");
        Font font1 = Font.decode("SansSerif-PLAIN-20");
        plot.setLabelFont(font);
        pieChart.getTitle().setFont(font1);
        pieChart.getLegend().setItemFont(font);

        return pieChart;
    }

    private static JFreeChart createBarChart(List<Book> books) {
        Map<String, Integer> kindCount = new HashMap<>();
        for (Book book : books) {
            String category = book.getKind();
            kindCount.put(category, kindCount.getOrDefault(category, 0) + 1);
        }

        List<Map.Entry<String, Integer>> sortedCategories = kindCount.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
//                .limit(5)
                .collect(Collectors.toList());

        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        for (int i = 0; i < sortedCategories.size(); i++) {
            Map.Entry<String, Integer> entry = sortedCategories.get(i);
            dataset.addValue(entry.getValue(), "Number of Books", entry.getKey());
        }

        JFreeChart barChart = ChartFactory.createBarChart(
                "书籍种类柱状图",
                "种类",
                "数量",
                dataset,
                PlotOrientation.VERTICAL,
                true, true, false);

        CategoryPlot plot = (CategoryPlot) barChart.getPlot();
        // 设置中文字体
        Font chineseFont = new Font("宋体", Font.PLAIN, 12);
        Font chineseFont1 = new Font("宋体", Font.PLAIN, 20);
        plot.getDomainAxis().setLabelFont(chineseFont);
        plot.getDomainAxis().setTickLabelFont(chineseFont);
        plot.getRangeAxis().setLabelFont(chineseFont);
        barChart.getTitle().setFont(chineseFont1);
        barChart.getLegend().setItemFont(chineseFont);

        return barChart;
    }
}
